// src/components/ImageUpload.tsx
import { Box, Button, VStack, Text } from '@chakra-ui/react';
import { useRef, useState } from 'react';
import { useErrorHandler } from '../hooks/useErrorHandler';
import { FileTypeError, FileSizeError, ImageLoadError } from '../utils/errorTypes';
import { createLogger } from '../utils/logger';

const logUpLoad = createLogger('imageUpload');

interface ImageUploadProps {
  onImageUpload: (imageUrl: string) => void;
}

// 支持的图片类型
const SUPPORTED_FORMATS = ['image/jpeg', 'image/png', 'image/gif', 'image/webp'];
const SUPPORTED_EXTENSIONS = ['.jpg', '.jpeg', '.png', '.gif', '.webp'];
const MAX_FILE_SIZE = 10 * 1024 * 1024; // 10MB

export const ImageUpload = ({ onImageUpload }: ImageUploadProps) => {
  const fileInputRef = useRef<HTMLInputElement>(null);
  const [isDragging, setIsDragging] = useState(false);
  const { /*handleError,*/ withErrorHandling } = useErrorHandler();

  const validateFile = (file: File): void => {
    logUpLoad.debug('Validating file:', ' name:', file.name, ' type:', file.type, ' size:', file.size);

    // 检查文件类型
    if (!SUPPORTED_FORMATS.includes(file.type)) {
      throw new FileTypeError(SUPPORTED_FORMATS.map(format => format.split('/')[1].toUpperCase()));
    }

    // 检查文件大小
    if (file.size > MAX_FILE_SIZE) {
      throw new FileSizeError(10);
    }

    // 额外检查：如果文件类型完全是未知的，也拒绝
    if (!file.type && !SUPPORTED_EXTENSIONS.some(ext => file.name.toLowerCase().endsWith(ext))) {
      throw new FileTypeError(SUPPORTED_FORMATS.map(format => format.split('/')[1].toUpperCase()));
    }
  };

  // 处理文件读取和上传的通用函数
  const processAndUploadFile = withErrorHandling(
    async (file: File) => {
      // 验证文件
      validateFile(file);

      const reader = new FileReader();

      await new Promise<void>((resolve, reject) => {
        reader.onload = (e) => {
          if (e.target?.result) {
            onImageUpload(e.target.result as string);
            resolve();
          } else {
            reject(new ImageLoadError('FileReader result is empty'));
          }
        };

        reader.onerror = () => {
          reject(new ImageLoadError('FileReader failed to read file'));
        };

        reader.readAsDataURL(file);
      });
    },
    'image-upload'
  );

  // 🔹 处理"选择图片"按钮的点击事件
  const handleButtonClick = () => {
    fileInputRef.current?.click();
  };

  // 🔹 处理文件选择（通过点击按钮）
  const handleFileSelect = (event: React.ChangeEvent<HTMLInputElement>) => {
    const file = event.target.files?.[0];
    if (!file) return;

    processAndUploadFile(file).catch((error) => {
      // 错误已经在 withErrorHandling 中处理了，这里只是为了确保 Promise 链完整
      console.log('File selection error handled:', error);
    });
  };

  // 🔹 处理拖拽进入上传区域的事件
  const handleDragOver = (event: React.DragEvent<HTMLDivElement>) => {
    event.preventDefault();
    setIsDragging(true);
  };

  // 🔹 处理拖拽离开上传区域的事件
  const handleDragLeave = (event: React.DragEvent<HTMLDivElement>) => {
    event.preventDefault();
    setIsDragging(false);
  };

  // 🔹 处理文件被拖放（Drop）到上传区域的事件 - 修复版本
  const handleDrop = (event: React.DragEvent<HTMLDivElement>) => {
    event.preventDefault();
    setIsDragging(false);

    // 获取拖放的文件列表
    const files = event.dataTransfer.files;
    if (files.length > 0) {
      const file = files[0]; // 只处理第一个文件

      // 使用相同的验证和处理逻辑
      processAndUploadFile(file).catch((error) => {
        // 错误已经在 withErrorHandling 中处理了，这里只是为了确保 Promise 链完整
        console.log('Drag and drop error handled:', error);
      });
    }
  };

  // 🔹 渲染组件 UI
  return (
    <Box
      border="2px dashed"
      borderColor={isDragging ? 'blue.500' : 'gray.300'}
      borderRadius="lg"
      p={6}
      textAlign="center"
      _hover={{ borderColor: 'blue.400' }}
      transition="border-color 0.2s"
      bg={isDragging ? 'blue.50' : 'transparent'}
      onDragOver={handleDragOver}
      onDragLeave={handleDragLeave}
      onDrop={handleDrop}
      cursor="pointer"
    >
      <VStack spacing={4}>
        <Text fontSize="lg" fontWeight="medium" color={isDragging ? 'blue.600' : 'gray.600'}>
          {isDragging ? '释放图片上传' : '上传图片'}
        </Text>
        <Text fontSize="sm" color={isDragging ? 'blue.500' : 'gray.500'}>
          支持 JPG, PNG, GIF, WEBP 格式，最大 10MB
        </Text>
        <Button colorScheme="blue" onClick={handleButtonClick}>
          选择图片
        </Button>
        <input
          ref={fileInputRef}
          type="file"
          accept="image/*"
          onChange={handleFileSelect}
          style={{ display: 'none' }}
        />
      </VStack>
    </Box>
  );
};
